using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Threading;
using Ares.Crypt;

namespace cb0tServer
{
    class Topics
    {
        private static Mutex mutex = new Mutex();
        private static List<TopicItem> topic_items = new List<TopicItem>();
        private static String main_topic = "welcome to my room";

        private static String Time()
        {
            DateTime d = DateTime.Now;
            int h = d.Hour;
            int m = d.Minute;
            String ap = "AM";

            if (h >= 12) ap = "PM";

            if (h > 12) h -= 12;

            if (h == 0) h += 12; // midnight is not 0 on a 12 hour clock

            return h + ":" + (m < 10 ? ("0" + m) : m.ToString()) + " " + ap;
        }

        public static void AddTopic(UserObject userobj, String topic)
        {
            if (userobj.vroom == 0) main_topic = topic;

            foreach (TopicItem a in topic_items)
            {
                if (userobj.vroom == a.vroom)
                {
                    a.topic = topic;
                    SaveTopics();
                    return;
                }
            }

            TopicItem ti = new TopicItem();
            ti.vroom = userobj.vroom;
            ti.topic = topic;
            topic_items.Add(ti);
            SaveTopics();
        }

        public static void RemoveTopic(UserObject userobj)
        {
            for (int i = 0; i < topic_items.Count; i++)
            {
                if (userobj.vroom == topic_items[i].vroom)
                {
                    topic_items.RemoveAt(i);
                    SaveTopics();
                }
            }
        }

        public static String GetTopic(UserObject userobj)
        {
            if (userobj.vroom > 0)
            {
                foreach (TopicItem a in topic_items)
                {
                    if (userobj.vroom == a.vroom)
                    {
                        return /*Encoding.UTF8.GetString(AresCrypt.d67(pre, 1488)) + */a.topic;
                    }
                }
            }

            if (Settings.clock)
            {
                String clock_topic = "";// Encoding.UTF8.GetString(AresCrypt.d67(pre, 1488));
                clock_topic += StringTemplate.GetString(99).Replace("+c", Time()).Replace("+t", main_topic);
                return clock_topic;
            }

            return /*Encoding.UTF8.GetString(AresCrypt.d67(pre, 1488)) +*/ main_topic;
        }

        public static String GetMainTopic()
        {
            return main_topic; // Encoding.UTF8.GetString(AresCrypt.d67(pre, 1488)) + main_topic;
        }

        public static String GetUDPTopic()
        {
          //  String str = main_topic; // Encoding.UTF8.GetString(AresCrypt.d67(pre, 1488)) + main_topic;
            String str = main_topic;
            while (Encoding.UTF8.GetByteCount(str) > 180)
                str = str.Substring(0, str.Length - 1);

            return str;
        }

        public static String GetMainTopic(bool no_prefix)
        {
            return main_topic;
        }

        public static void SetVirtualTopic(UserObject userobj, String text)
        {
            userobj.SendOutboundPacket(ServerOutboundPackets.TopicFirstPacket(/*Encoding.UTF8.GetString(AresCrypt.d67(pre, 1488)) + */text));
        }

        public static void SetVirtualTopic(ushort vroom, String text)
        {
            UserPool.Broadcast(vroom, ServerOutboundPackets.TopicFirstPacket(/*Encoding.UTF8.GetString(AresCrypt.d67(pre, 1488)) + */text));
        }

        public static void SetVirtualTopic(String text)
        {
            UserPool.Broadcast(ServerOutboundPackets.TopicFirstPacket(/*Encoding.UTF8.GetString(AresCrypt.d67(pre, 1488)) + */text));
        }

        public static void LoadTopics()
        {
            topic_items.Clear();
            main_topic = "welcome to my room";

            if (!File.Exists(sb0t_winGUI.RunOnceFileUpdater.sbotpath + "data/topics.xml")) return;

            try
            {
                FileStream f = new FileStream(sb0t_winGUI.RunOnceFileUpdater.sbotpath + "data/topics.xml", FileMode.Open);
                XmlReader xml = XmlReader.Create(new StreamReader(f));

                xml.MoveToContent();
                xml.ReadSubtree().ReadToFollowing("topics");

                while (xml.ReadToFollowing("topic"))
                {
                    TopicItem a = new TopicItem();

                    xml.ReadSubtree().ReadToFollowing("vroom");
                    a.vroom = ushort.Parse(xml.ReadElementContentAsString());
                    xml.ReadToFollowing("text");
                    a.topic = Encoding.UTF8.GetString(Convert.FromBase64String(xml.ReadElementContentAsString()));

                    topic_items.Add(a);

                    if (a.vroom == 0) main_topic = a.topic;
                }

                xml.Close();
                f.Flush();
                f.Close();
            }
            catch { }
        }

        private static void SaveTopics()
        {
            mutex.WaitOne();

            try
            {
                XmlWriterSettings appearance = new XmlWriterSettings();
                appearance.Indent = true;
                XmlWriter xml = XmlWriter.Create(sb0t_winGUI.RunOnceFileUpdater.sbotpath + "data/topics.xml", appearance);

                xml.WriteStartDocument();
                xml.WriteStartElement("topics");

                foreach (TopicItem a in topic_items)
                {
                    xml.WriteStartElement("topic");
                    xml.WriteElementString("vroom", a.vroom.ToString());
                    xml.WriteElementString("text", Convert.ToBase64String(Encoding.UTF8.GetBytes(a.topic)));
                    xml.WriteEndElement();
                }

                xml.WriteEndElement();
                xml.WriteEndDocument();
                xml.Flush();
                xml.Close();
            }
            catch { }

            mutex.ReleaseMutex();
        }

    }

    class TopicItem
    {
        public String topic;
        public ushort vroom;
    }
}
